//
//  SEGCommunitySocialManager.m
//  SEGUhomeSommunitySocial
//
//  Created by 揭婧雯 on 2018/3/28.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGCommunitySocialManager.h"
#import "SEGProfileManager.h"
#import "SEGAnalyseBehaviorManager.h"
#import "SEGUtils.h"
#import "SEGFindDictionaryInfoManagr.h"
#import "NSObject+SEGModel.h"
#import "SEGBasicBussinessNotificationDefine.h"

//#if __has_include(<SEGPlatform/SEGPlatformHeader.h>)
//#import <SEGPlatform/SEGPlatformHeader.h>
//#else
//#import "SEGPlatformHeader.h"
//#endif
#import "SEGBussinessConstHeader.h"
#import "SEGPlatformManager.h"


@interface SEGCommunitySocialManager ()

/** 集市列表总页数 */
@property (nonatomic, assign) NSInteger marketTotalSize;

@end

@implementation SEGCommunitySocialManager

///  新增点赞浏览
///  @param objId    被点赞或浏览主题对象
///  @param objType  被点赞或浏览主题对象类型 1 画报2问题 3评论 4问题答案
///  @param type     操作类型 1 点赞 2 浏览 3 收藏 其他操作有需要后续扩展
///  @param creator  评论者的用户
///  @param objPicUrlForMsg  消息图片 主要是 2手 闲置 帮帮
///  @param objTitleForMsg  消息标题,如果是对PGC或者话题等系统发起的 objTitleForMsg为对应的标题，帮帮则为帮帮的标题（即问题的内容）否则objTitleForMsg为 评论内容
///  @param byReviewUserId  被点赞对象的用户ID，即记录创建者的用户Id
///  @param communityName  小区名称 来自 XX市 XX小区
///  @param parentObjId    父级Id ，例如对问题答案进行回复的话 parentObjId为问题ID
- (void)requestPictorialPraiseAttentByObjId:(NSString*)objId
                                    ObjType:(NSString*)objType
                                       Type:(NSString*)type
                                    Creator:(NSString*)creator
                            objPicUrlForMsg:(NSString*)objPicUrlForMsg
                             objTitleForMsg:(NSString*)objTitleForMsg
                             byReviewUserId:(NSString*)byReviewUserId
                              communityName:(NSString*)communityName
                                parentObjId:(NSString*)parentObjId
                              parentObjType:(NSInteger)parentObjType
                                   Finished:(SEGRequestCallBack)finished
{
    [self requestPictorialPraiseAttentByObjId:objId ObjType:objType Type:type Creator:creator objPicUrlForMsg:objPicUrlForMsg objTitleForMsg:objTitleForMsg byReviewUserId:byReviewUserId communityName:communityName parentObjId:parentObjId parentObjType:parentObjType isTopicPraise:NO topicID:nil Finished:finished];
}

/// 话题列表点赞
/// @param objId    被点赞或浏览主题对象
/// @param objType  被点赞或浏览主题对象类型 1 画报2问题 3评论 4问题答案
/// @param type     操作类型 1 点赞 2 浏览 3 收藏 其他操作有需要后续扩展
/// @param creator  评论者的用户
/// @param objPicUrlForMsg  消息图片 主要是 2手 闲置 帮帮
/// @param objTitleForMsg  消息标题,如果是对PGC或者话题等系统发起的 objTitleForMsg为对应的标题，帮帮则为帮帮的标题（即问题的内容）否则objTitleForMsg为 评论内容
/// @param byReviewUserId  被点赞对象的用户ID，即记录创建者的用户Id
/// @param communityName  小区名称 来自 XX市 XX小区
/// @param parentObjId    父级Id ，例如对问题答案进行回复的话 parentObjId为问题ID
/// @param parentObjType parentObjType description
/// @param isTopicPraise 是否是话题点赞
/// @param topicID 如果是话题点赞，需要传话题ID
/// @param finished finished description
- (void)requestPictorialPraiseAttentByObjId:(NSString*)objId
                                    ObjType:(NSString*)objType
                                       Type:(NSString*)type
                                    Creator:(NSString*)creator
                            objPicUrlForMsg:(NSString*)objPicUrlForMsg
                             objTitleForMsg:(NSString*)objTitleForMsg
                             byReviewUserId:(NSString*)byReviewUserId
                              communityName:(NSString*)communityName
                                parentObjId:(NSString*)parentObjId
                              parentObjType:(NSInteger)parentObjType
                              isTopicPraise:(BOOL)isTopicPraise
                                    topicID:(NSString*)topicID
                                   Finished:(SEGRequestCallBack)finished
{
    //字典为空的闪退，数据校验
    NSMutableDictionary* params = [@{
                             @"objId" : objId,
                             @"objType" : objType,
                             @"type" : type,
                             @"creator" : creator,
                             @"objPicUrlForMsg" : objPicUrlForMsg,
                             @"objTitleForMsg" : objTitleForMsg,
                             @"byReviewUserId" : byReviewUserId,
                             @"communityName" : communityName,
                             @"parentObjId" : parentObjId,
                             @"userId" : kAccountUserID,
                             @"parentObjType" : @(parentObjType)
                             } mutableCopy];
    
    // 话题点赞需要添加字段，否则在消息列表跳转会有问题
    if (isTopicPraise) {
        params[@"operationType"] = @(SEGNeighbourhoodOperationType_Topic);
    }
    
    //定义参数type的变量，让type_值能传给block回调
    __block NSString *type_ = type;
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/praiseAttent/save.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if ([result objectForKey:@"data"]) {
            self.isPraise = YES;
        }
        else {
            self.isPraise = NO;
        }
        
        NSString *integralCode = @"";
        NSString *module = @"";
        NSString *businessID = @"";
        
        if ([type_ isEqualToString:@"1"]) {//点赞后进行积分行为奖励
            integralCode = SEGIntegralCode.like;
            module = SEGIntegralModule.neighborhoodCircle;
            if (isTopicPraise) {
                module = SEGIntegralModule.topicDetail;
                businessID = topicID;
            }
        }else if( [type_ isEqualToString:@"3"]){ //收藏后进行积分行为奖励
            integralCode = SEGIntegralCode.addToFavorites;
            module = SEGIntegralModule.articleDetail;
            businessID = objId;
        }
        
        if (integralCode.length > 0) {
            [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:integralCode module:module businessID:businessID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            }];
        }
        finished(YES, codeType, errorMessage);
        
    }];
    
}


- (void)requestCancelPraiseOrCollectByUserId:(NSString*)userId
                                       objId:(NSString*)objId
                                     objType:(NSString*)objType
                                        type:(NSString*)type
                                    Finished:(SEGRequestCallBack)finished
{
    //字典为空的闪退，数据校验
    NSDictionary* params = @{
                             @"userId" : ValueToString(userId),
                             @"objId" : ValueToString(objId),
                             @"objType" : ValueToString(objType),
                             @"type" : ValueToString(type)
                             };
    
    //定义参数type的变量，让type_值能传给block回调
    __block NSString *type_ = type;
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/praiseAttent/cancelPraiseOrCollect.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        if ([result objectForKey:@"data"]) {
            self.isPraise = YES;
        }
        else {
            self.isPraise = NO;
        }
        
        NSString *integralCode = @"";
        
        if ([type_ isEqualToString:@"1"]) {//点赞后进行积分行为奖励
            integralCode = SEGIntegralCode.cancelLike;
        }else if( [type_ isEqualToString:@"3"]){ //收藏后进行积分行为奖励
            integralCode = SEGIntegralCode.cancelCollect;
        }
        
        if (integralCode.length > 0) {
            [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:integralCode finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
            }];
        }
        
        finished(YES, codeType, errorMessage);
    }];
    
}

/**
 * 参与话题、发布帮帮
 * @author Wendy
 * @param params  发布参数
 */
- (void)requestSaveQuizWithParams:(NSDictionary *)params
                         Finished:(SEGRequestCallBack)finished
{
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/quiz/saveQuiz.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        finished(YES, codeType, errorMessage);
    }];
    
}

/**
 * 获取导航栏区域类型的下拉菜单
 * @author Wendy
 */
- (void)requesPublishScopeListFinished:(SEGRequestCallBack)finished
{
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/publishScope/list.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:nil finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        if ([result valueForKey:@"data"] && [[result valueForKey:@"data"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary* dicData = [result valueForKey:@"data"];
            
            if (![dicData objectForKey:@"publishScopeList"]) {
                
                finished(NO, @"", @"数据返回为空！"); //数据返回正常，但是数据为空
                return;
            }
            
            NSArray* pictorialList = [dicData valueForKey:@"publishScopeList"];
            
            NSMutableArray* arrM = [NSMutableArray arrayWithCapacity:pictorialList.count];
            
            for (NSDictionary* dic in pictorialList) {
                PublishScopeListModel* _model = [PublishScopeListModel yy_modelWithDictionary:dic];
                [arrM addObject:_model];
            }
            
            self.publishScopeList = arrM;
            
            finished(YES, codeType, errorMessage);
        }
        finished(isSuccessed, codeType, errorMessage);
    }];
}

/**
 * 对评论点赞
 * @author Wendy
 * @param objId    被点赞或浏览主题对象
 * @param objType  被点赞或浏览主题对象类型 1 画报2问题 3评论 4问题答案
 * @param objPicUrlForMsg  消息图片 主要是 2手 闲置 帮帮
 * @param objTitleForMsg  消息标题,如果是对PGC或者话题等系统发起的 objTitleForMsg为对应的标题，帮帮则为帮帮的标题（即问题的内容）否则objTitleForMsg为 评论内容
 * @param byReviewUserId  被点赞对象的用户ID，即记录创建者的用户Id
 * @param parentObjId    父级Id ，例如对问题答案进行回复的话 parentObjId为问题ID
 * @param parentObjType
 * @param operationType 邻里圈类型 邻里圈相关点赞传 其他地方不传
 * @param isParent 是否是对主数据进行评论 1：是 2：不是
 * @param finished 回调结果
 */
- (void)requestPraiseAttentByObjId:(NSString*)objId
                           ObjType:(NSString*)objType
                   objPicUrlForMsg:(NSString*)objPicUrlForMsg
                    objTitleForMsg:(NSString*)objTitleForMsg
                    byReviewUserId:(NSString*)byReviewUserId
                       parentObjId:(NSString*)parentObjId
                     parentObjType:(NSString*)parentObjType
                     operationType:(NSString *)operationType
                          isParent:(NSString *)isParent
                          Finished:(SEGRequestCallBack)finished
{
    SEGProfileModel* sysAccount = [SEGProfileManager sharedManager].profile;
    NSString* communityName = [NSString stringWithFormat:@"来自%@ %@", sysAccount.city, sysAccount.communityName];
    //字典为空的闪退，数据校验
    NSDictionary* tempDict = @{
                               @"objId" : objId,
                               @"objType" : objType,
                               @"type" : @"1",//点赞固定1
                               @"creator" : sysAccount.nickname,
                               @"objTitleForMsg" : objTitleForMsg,
                               @"byReviewUserId" : byReviewUserId,
                               @"communityName" : communityName,
                               @"parentObjId" : parentObjId,
                               @"userId" : kAccountUserID,
                               @"parentObjType" : parentObjType
                               };
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithDictionary:tempDict];
    if (objPicUrlForMsg) {
        [params setObject:objPicUrlForMsg forKey:@"objPicUrlForMsg"];
    }
    if (operationType) {
        [params setObject:operationType forKey:@"operationType"];
    }
    if (isParent) {
        [params setObject:isParent forKey:@"isParent"];
    }
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/praiseAttent/save.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        NSString *module = @"";
        NSString *businessID = nil;
        // 对PGC评论点赞
        if (parentObjType.integerValue == SEGUserType_PICTORIAL) {
            module = SEGIntegralModule.articleDetail;
            businessID = parentObjId;
        } else {
            module = SEGIntegralModule.neighborhoodCircle;
        }
        [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.like module:module businessID:businessID finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        }];
        
        finished(YES, codeType, errorMessage);
    }];
}

/**
 * 取消点赞
 * @author Wendy
 * @param objId 被取消对象ID
 * @param objType 被取消对象类型
 * @param finished 回调结果
 */
- (void)requestCancelPraiseByobjId:(NSString*)objId
                           objType:(NSString*)objType
                          Finished:(SEGRequestCallBack)finished
{
    //字典为空的闪退，数据校验
    NSDictionary* params = @{
                             @"userId" : kAccountUserID,
                             @"objId" : ValueToString(objId),
                             @"objType" : ValueToString(objType),
                             @"type" : @"1"
                             };
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/praiseAttent/cancelPraiseOrCollect.json",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:POST URLString:urlString parameters:params finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        
        if (!isSuccessed) {
            finished(NO, codeType, errorMessage);
            return;
        }
        
        [[SEGAnalyseBehaviorManager sharedManager] requestIntegralGrowthWithCode:SEGIntegralCode.cancelLike finished:^(BOOL isSuccessed, id result, NSString *codeType, NSString *errorMessage) {
        }];
        
        
        finished(YES, codeType, errorMessage);
        
    }];
    
}

-(void)requestFindDictionaryInfoByCode:(NSString *)code Finished:(SEGNetworkReponse)finished
{
    NSDictionary *params = @{@"code":code};
    [[SEGFindDictionaryInfoManagr sharedManager] requestDictionaryInfoByCode:code completed:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull codeType, NSString * _Nonnull errorMessage) {
        
        NSDictionary *dict = [result objectForKey:@"data"];
        NSArray *array = [dict objectForKey:@"result"];
        
        if (!array || array.count <= 0) {
            finished(NO,  result, codeType, errorMessage);
            return;
        }
        
        NSMutableArray* arrM = [NSMutableArray array];
        [array enumerateObjectsUsingBlock:^(NSDictionary* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            SEGMarketTypeModel *_model = [SEGMarketTypeModel initWithDictionary:obj];
            [arrM addObject:_model];
        }];
        
        self.dataSourceMarketTypeList = [arrM copy];
        finished(isSuccessed,  result, codeType, errorMessage);
    }];
}

/// 集市大类
-(void)requestMarketTypeList:(SEGNetworkReponse)finished
{
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v4/getMarketTypeList",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET
                                        URLString:urlString
                                       parameters:nil
                                         finished:^(BOOL isSuccessed,
                                                    id result,
                                                    NSString *codeType,
                                                    NSString *errorMessage) {
                                             
                                             NSDictionary *dict = [result objectForKey:@"data"];
                                             NSArray *array = [dict objectForKey:@"marketList"];
                                             
                                             if (array && [array isKindOfClass:[NSArray class]]) {
                                                 
                                                 self.marketTypeList = [NSMutableArray array];
                                                 [array enumerateObjectsUsingBlock:^(NSDictionary* _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                                                     SEGNewMarketTypeModel *_model = [SEGNewMarketTypeModel yy_modelWithDictionary:obj];
                                                     [self.marketTypeList addObject:_model];
                                                 }];
                                             }
                                             
                                             finished(isSuccessed,  result, codeType, errorMessage);
                                         }];
}


//根据类别查询集市
-(void)requestMarketListByTypeID:(NSString *)typeId
                         scopeId:(NSString *)scopeId
                          pageNo:(NSString *)pageNo
                        Finished:(SEGNetworkReponse)finished {
    NSInteger pageLimit = 20;
    [self requestMarketListByTypeID:typeId scopeId:scopeId pageNo:pageNo pageLimit: pageLimit cityID:[SEGProfileManager sharedManager].profile.cityId Finished:finished];
}

//根据类别查询集市
-(void)requestMarketListByTypeID:(NSString *)typeId
                         scopeId:(NSString *)scopeId
                          pageNo:(NSString *)pageNo
                       pageLimit:(NSInteger)pageLimit
                          cityID:(NSString *)cityID
                        Finished:(SEGNetworkReponse)finished {
    
    /**
     最后一页, 无需再次请求接口
     
     条件一: pageNum != 1, 防止下拉刷新时 return;
     条件二: pageNum > 总页数, 说明已经拿到所有数据, 无需再次调用接口 return;
     */
    if (([pageNo integerValue] != 1) && [pageNo integerValue] > _marketTotalSize) {
        finished(NO, nil, nil, kNoMoreDataContent);
        return;
    }
    
    // 异常数据处理
    typeId = typeId ?: @"";
    scopeId = scopeId ?: @"";
    pageNo = pageNo ?: @"";
    NSMutableDictionary *params = [@{@"typeId" : typeId,
                             @"scopeId" : scopeId,
                             @"pageLimit" : @(pageLimit),
                             @"pageNo" : pageNo,
                             } mutableCopy];
    if ([pageNo isEqualToString:@"1"]) {
        self.marketList = [NSMutableArray array];
    }
    if (cityID.length > 0) {
        params[@"cityId"] = cityID;
    }
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/cms-api/api/v4/getMarketListByType",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET
                                        URLString:urlString
                                       parameters:params
                                         finished:^(BOOL isSuccessed,
                                                    id result,
                                                    NSString *codeType,
                                                    NSString *errorMessage) {
                                             
                                             NSDictionary* dicData = [result valueForKey:@"data"];
                                             self.marketTotalSize = [dicData[@"totalPage"] integerValue]; // 总页数
                                             if ((!dicData) || (![dicData isKindOfClass:[NSDictionary class]])) {
                                                 finished(NO, result, codeType, errorMessage);
                                                 return;
                                             }
                                             NSArray* goodList = [dicData valueForKey:@"goodList"];
                                             
                                             for (NSDictionary* dic in goodList) {
                                                 NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:dic];
                                                 [temp setObject:@"0" forKey:@"isDetailView"];//不是详情页
                                                 SEGQueryGoodsIdelModel* _model = [SEGQueryGoodsIdelModel initWithDictionary:temp];
                                                 __block BOOL isNotLike = NO;
                                                 //本地过滤不感兴趣的数据
                                                 NSDictionary *tempDict = [[NSUserDefaults standardUserDefaults] objectForKey:kNeighborhoodNotLikeArray];
                                                 if (tempDict && [tempDict isKindOfClass:[NSDictionary class]]) {
                                                     __block NSArray *array;
                                                     if ([tempDict objectForKey:kAccountUserID]) {
                                                         array = [tempDict objectForKey:kAccountUserID];
                                                     }
                                                     if (array && [array isKindOfClass:[NSArray class]]) {
                                                         [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
                                                             NSString *objType = ValueToString(dic[@"objType"]);
                                                             NSString *objId = ValueToString(dic[@"objId"]);
                                                             NSString *currentObjType = [SEGBasicBussinessEnums getSEGEnumIdelExchange:[_model.type integerValue]];
                                                             if([objType isEqualToString:currentObjType] && [objId isEqualToString:ValueToString(_model.goodsId)]) {
                                                                 isNotLike = YES;
                                                                 *stop = YES;
                                                             }
                                                         }];
                                                     }
                                                 }
                                                 __block BOOL isReported = NO;
                                                 //本地过滤举报过的数据
                                                 tempDict = [[NSUserDefaults standardUserDefaults] objectForKey:kNeighborhoodReportedArray];
                                                 if (tempDict && [tempDict isKindOfClass:[NSDictionary class]]) {
                                                     __block NSArray *array;
                                                     if ([tempDict objectForKey:kAccountUserID]) {
                                                         array = [tempDict objectForKey:kAccountUserID];
                                                     }
                                                     if (array && [array isKindOfClass:[NSArray class]]) {
                                                         [array enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
                                                             NSString *objType = ValueToString(dic[@"objType"]);
                                                             NSString *objId = ValueToString(dic[@"objId"]);
                                                             NSString *currentObjType = [_model convertToObjType];
                                                             if([objType isEqualToString:currentObjType] && [objId isEqualToString:ValueToString(_model.goodsId)]) {
                                                                 isReported = YES;
                                                                 *stop = YES;
                                                             }
                                                         }];
                                                     }
                                                 }
                                                 
                                                 if ((!isNotLike) && (!isReported)) {
                                                     if ([_model.status integerValue] == SEGEnumIdleStatus_Idle) {
                                                         [self.marketList addObject:_model];
                                                     }
                                                 }
                                             }
                                             
                                             finished(isSuccessed,  result, codeType, errorMessage);
                                         }];
}

#pragma mark - getter
- (NSArray<PublishScopeListModel*>*)publishScopeList
{
    
    if (!_publishScopeList) {
        
        _publishScopeList = [NSArray array];
    }
    
    return _publishScopeList;
}

- (NSArray<SEGMarketTypeModel*>*)dataSourceMarketTypeList
{
    if (!_dataSourceMarketTypeList)
    {
        _dataSourceMarketTypeList = [NSArray array];
    }
    return _dataSourceMarketTypeList;
}

- (NSMutableArray<SEGNewMarketTypeModel *> *)marketTypeList
{
    if (!_marketTypeList) {
        _marketTypeList = [NSMutableArray array];
    }
    return _marketTypeList;
}

- (NSMutableArray<SEGQueryGoodsIdelModel *> *)marketList
{
    if (!_marketList) {
        _marketList = [NSMutableArray array];
    }
    return _marketList;
}


@end
